package threads;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.LinkedList;

import com.audiobuddy.serializables.Song;

import domain.ClientDomainController;


public class MulticastPlaylistThread extends Thread {
	
	private static final int PORT = 4444;
	private byte[] buffer;
	private DatagramPacket inPacket;
	private MulticastSocket socket;
	private ClientDomainController dc;

	public MulticastPlaylistThread(ClientDomainController dc){
		super("multicastPlaylistReceiver");
		this.dc = dc;
		try {
			socket = new MulticastSocket(PORT);
			InetAddress address = InetAddress.getByName("230.0.0.1");
			socket.joinGroup(address);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		super.run();
		while(true){
			try{
				buffer = new byte[4096];
				inPacket = new DatagramPacket(buffer, buffer.length);
				socket.receive(inPacket);
				String inString = new String(inPacket.getData(), 0, inPacket.getLength());
				if(inString.startsWith("current")){
					String current = inString.replaceFirst("current::", "");
					System.out.println("currently playing received: " + current);
					dc.showCurrentSong(current);
				}
				
				ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
				ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
				dc.setSongs((LinkedList<Song>) ois.readObject());
				System.out.println("received multicast playlist");
				
			}catch (IOException e) {
				System.out.println("IOException on multicast receive playlist: " + e);
			} catch (ClassNotFoundException e) {
				System.out.println("class not found on receiving playlist multicast");
			}
			
			
		}
	}
	
	
	
	

}
